import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let car = JSON.parse(localStorage.getItem('car')||'[]')
export default new Vuex.Store({
  state: {
    count:0,
    //{id:商品ID,count:商品购买数量,price:价格,selected:是否选中,默认true}
    car:car
  },
  mutations: {
    add(state,goodsinfo){
      var status = false
      state.car.some( item =>{
        if(item.id == goodsinfo.id){
          item.count += goodsinfo.count
          status = true
          return true
        }
      })
      if(!status){
        state.car.push(goodsinfo)
      }
      localStorage.setItem('car',JSON.stringify(state.car))
    },
    changeSelect(state,goodsdata){
      state.car.some(item=>{
        if(item.id == goodsdata.id){
          item.selected = goodsdata.selected
          return true
        }
      })
      localStorage.setItem("car", JSON.stringify(state.car));
    },
    changeCount(state,data){
      state.car.some(item=>{
        if(item.id == data.id){
          item.count = data.count
          return true
        }
      })
      localStorage.setItem("car", JSON.stringify(state.car));
    },
    delgoods(state,id){
      state.car.some((item,i)=>{
        if(item.id == id){
          state.car.splice(i,1)
          return true
        }
      })
      localStorage.setItem("car", JSON.stringify(state.car));
    }
  },
  getters:{
    getAllCounts(state){
      let c = 0;
      state.car.forEach(item =>{
        c += item.count
      })
      return c
    },
    getSelected(state){
      let goodsSelected = {}
      state.car.forEach(item =>{
          goodsSelected[item.id] = item.selected
        }
      )
      return goodsSelected
    },
    getCount(state){
      let goodsCount = {}
      state.car.forEach(item=>{
        goodsCount[item.id] = item.count
      })
      return goodsCount
    }
  },
  actions: {

  }
})
